<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="line-chart-all">
    <div id="lineChart1" class="line-chart-item">
      <div
        v-if="showNoData"
        style="
          width: 100%;
          height: 90%;
          font-size: 1rem;
          color: #999;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
        "
      >
        暂无统计数据
      </div>
    </div>
  </div>
</template>

<script setup>
import * as VTable from '@visactor/vtable';
import VChart from '@visactor/vchart';
const props = defineProps(['lineData']);
VTable.register.chartModule('vchart', VChart);
const showNoData = ref(true);
const CONTAINER_ID = 'lineChart1';

let vlineInstance = null;

watch(
  () => props.lineData,
  (newLineData) => {
    // 销毁旧实例
    if (vlineInstance) {
      vlineInstance.release();
    }
    if (newLineData?.dataList?.length && newLineData?.monthes?.length) {
      // 重新初始化图表
      initLineChart(newLineData.dataList, newLineData.monthes);

      showNoData.value = false;
    } else {
      showNoData.value = true;
    }
  },
  { deep: true, immediate: true }
);

onBeforeUnmount(() => {
  vlineInstance?.release();
});

const initLineChart = (dataList, monthes) => {
  const transformedData = [];
  dataList.forEach((item) => {
    item.data.forEach((monthData) => {
      transformedData.push({
        type: monthData.month,
        country: item.name,
        value: monthData.dataCount
      });
    });
  });

  const spec = {
    type: 'line',
    data: {
      values: transformedData
    },
    stack: true,
    xField: 'type',
    yField: 'value',
    axes: [
      {
        type: 'linear',
        orient: 'left',
        label: {
          formatMethod(val) {
            return `${val / 10000}w`;
          }
        }
      }
    ],
    seriesField: 'country',
    line: {
      style: {
        curveType: 'monotone'
      }
    },
    point: {
      style: {
        size: 0,
        fill: 'white',
        stroke: null,
        lineWidth: 2
      },
      state: {
        dimension_hover: {
          size: 10
        }
      }
    },
    legends: {
      visible: true,
      orient: 'top',
      position: 'middle',
      item: {
        label: {
          style: {
            fontSize: 8
          }
        }
      }
    }
  };

  const vchart = new VChart(spec, { dom: CONTAINER_ID });
  vchart.renderSync();
  vlineInstance = vchart;
};
</script>

<style lang="scss" scoped>
.line-chart-all {
  width: 100%;
  height: 100%;
  .line-chart-item {
    width: 100%;
    height: 85%;
  }
}
</style>
